<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\common\Common;
use app\admin\model\Basicdata;
use app\admin\model\Image;
use app\admin\model\Area;

use think\Db;
use think\Request;

class Farmbaseland extends Base
{

    public function _initialize() {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;

        $this->searchFields = [
            'name' => [
                'label'     => '基地名称',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        // 基地类型
        $typeList = Basicdata::where('type', 'baseland')->select();

        $this->assign('typeList', $typeList);
    }

    public function index(){
        return parent::index();
    }

    public function add(Request $request){
        return parent::add($request);
    }

    public function addPost(Request $request, $redirect='') {
        $model = model($this->model);

        //save data
        if ($request->isAjax()) {
            $data = $request->param();
            // Insert data
            $data['id'] = BaseHelper::getUUID();
            $data['createDate'] = time();
            $data['createOper'] = $this->admin->id;
            $data['imgUrl'] = $data['coverImg'];

            $result = $model->save($data);
            if($result !== false) {
                // 单图
                if(isset($data['imgId']) && !empty($data['imgId'])){
                    Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages']);
                }
                // 多图
                if(isset($data['imgIds']) && !empty($data['imgIds'])){
                    foreach ((array)$data['imgIds'] as $key => $item) {
                        Image::where('id', $item)->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }

                // Query执行后的操作
                $model->_after_insert($data);

                // 写入日志
                $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                if ($redirect) {
                    return $this->success('添加成功！', $redirect);
                } else {
                    return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('');
        }
    }

    public function edit(Request $request) {
        $model = model($this->model);
        $id = $request->param('id');
        $info = $model->where('id',$id)->find();

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        // 图集
        $imagesList = Image::where(['relatedId' => $info->id, 'tag' => 'imglist'])->where('imgUrl', 'neq', $info->imgUrl)->order('sorting ASC')->select();
        $this->assign('imagesList', $imagesList);

        $areaMdl = new Area();
        $city = BaseHelper::makeOptions(
            $areaMdl,
            ['level' => 1],
            ['id' => 'asc']
        );
        $this->assign('city',$city);

        $ids = $info['cityId'].','.$info['xianId'].','.$info['townId'];
        $area = Area::where('id','in',$ids)->field('name')->select();
        $str = [];
        foreach ($area as $v) {
            $str[] = $v['name'];
        }
        $this->assign('area',implode('-', $str));

        return $this->view->fetch($this->editView, ['info' => $info]);
    }

    public function editPost(Request $request, $redirect='') {
        $model = model($this->model);

        //save data
        if ($request->isAjax()) {
            $data = $request->param();
            // Update data
            $data['updateDate'] = time();
            $data['updateOper'] = $this->admin->id;
            $data['imgUrl'] = $data['coverImg'];

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            if($result !== false) {
                // 单图
                if (isset($data['imgId']) && !empty($data['imgId'])) {
                    Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages']);
                }
                // 多图
                if (isset($data['imgIds']) && !empty($data['imgIds'])) {
                    foreach ((array)$data['imgIds'] as $key => $item) {
                        Image::where('id', $item)->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }

                // Query执行后的操作
                $model->_after_update($data);

                // 写入日志
                $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                if ($redirect) {
                    return $this->success('编辑成功！', $redirect);
                } else {
                    return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('error !');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        if($id){
            // 该基地是否已被使用
            $usedInfo = $this->isUsed($id);
            if($usedInfo['code'] != 1){
                return $this->error($usedInfo['msg']);
            }

            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                if($result !== false){
                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 检查名称是否已存在
     */
    public function checkName(){
        if($this->request->isAjax()){
            $name = $this->request->param('name');
            $model = model($this->model);

            $result = $model->where(['name' => $name])->field('name')->find();

            if($result){
                return json(['status' => 1]);
            }else{
                return json(['status' => 0]);
            }
        }
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($id){
        if(!$id){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有使用该基地的产品
        $productWhere = [
            'baselandId' => $id,
        ];
        $product = \app\admin\model\Product::where($productWhere)->find();
        if($product){
            return ['code' => 0, 'msg' => '有使用该基地的产品，请先删除产品'];
        }


        return ['code' => 1, 'msg' => ''];
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            // 所在地
            $item['area'] = getArea($item);
            // 基地类型
            $item['typeId'] = Basicdata::where(['id' => $item['typeId']])->value('name');
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }

            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }
}